<?php
class AdminCmsForm extends VTNSCmsForm
{	
	public function configure()
    {
		$cms = $this->getDefaults();
		$this->setWidgets(array(
                'name'                			=> new sfWidgetFormInput(),
				'cms_category_id'				=> new SfWidgetFormChoice(array('choices' => $this->getCmsCategoryParent(), 'default' => 1)),
				'picture'           			=> new sfWidgetFormInputFile(),
				'description'          			=> new sfWidgetFormTextarea(),
				'content'           			=> new sfWidgetFormTextarea(),
				'link'		           			=> new sfWidgetFormInput(),
				'tags'							=> new sfWidgetFormInput(),
				'is_active'						=> new sfWidgetFormInputCheckbox(),
				));
		$this->setValidators(array(
	            'name'           		    	=>  new sfValidatorString(array('required' => false)),
	            'description'                	=>  new sfValidatorString(array('required' => false))
		));
        $this->widgetSchema->setNameFormat('cms[%s]');
		$this->widgetSchema->setLabels(array(
				'name'							=> 'Tiêu đề',
				'cms_category_id'				=> 'Danh mục',
				'picture'						=> 'Hình ảnh đại diện',
				'description'					=> 'Mô tả',
				'content'						=> 'Nội dung',
				'link'							=> 'Link',
				'tags'							=> 'Tags',
				'is_active'						=> 'Kích hoạt',
		));
	}
	
	private function getCmsCategoryParent()
	{
		$parents = array();
		$level = 0;

		$c = Doctrine_Query::create()
			->select('c.*')
			->from('VtnsCmsCategory c')
			->where('c.parent_id = ?', 0)
			->orderBy('c.position');
		
		$results = $c->fetchArray();
		foreach ($results as $result)
		{
			$str = "";
			
			if ($level > 0)
			{
				for($i=0;$i<$level;$i++)
				{
					$str .= " ";
				}
				$str .= "- ";
			}
			$parents[$result['cms_category_id']] = $str.$result['name'];
            $arr_temp = $this->getTreeCmsCategory($result['cms_category_id'], $level+2);
			if ($arr_temp)
                $parents = $this->arr_merge($parents, $arr_temp);
		}

		return $this->arr_merge(array(0=>'Không có mục cha'),$parents);
	}
	
	private function getTreeCmsCategory($parent_id, $level)
	{
		$parents = array();
		$c = Doctrine_Query::create()
			->from('VtnsCmsCategory c')
			->where('c.parent_id = ?', $parent_id)
			->orderBy('c.position');
		$results = $c->fetchArray();
		foreach ($results as $result)
		{
			$str = "";
			
			if ($level > 0)
			{
				for($i=0;$i<$level;$i++)
				{
					$str .= "&nbsp;&nbsp;";
				}
				$str .= "- ";
			}
			$parents[$result['cms_category_id']] = $str.$result['name'];
            $arr_temp = $this->getTreeCmsCategory($result['cms_category_id'], $level+2);
			if ($arr_temp)
                $parents = $this->arr_merge($parents, $arr_temp);
		}
		return $parents;
	}
    private function arr_merge($arr1, $arr2)
    {
        foreach ($arr2 as $key => $value)
        {
            $arr1[$key] = $value;
        }
        return $arr1;
    }
}
?>